<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="40%"
    :before-close="handleClose"
  >
    <div class="single-dialog">
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="单页标题" prop="page_title" style="width: 100%">
          <el-input
            placeholder="输入单页标题"
            style="width: 100%"
            v-model="ruleForm.page_title"
          />
        </el-form-item>

        <el-form-item label="内容" style="width: 100%">
          <richPage ref="richPageRef" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { addApi, saveApi } from "@/plugins/api/shoppingContent/single";
import { uploadImgApi } from "@/plugins/api/upload";
const props = defineProps({
  treeData: {
    type: Array,
    default: [],
  },
});
let ruleForm = ref({});
let rules = {
  page_title: [{ required: true, message: "请输入单页标题", trigger: "blur" }],
};
let dialogVisible = ref(false);
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {});
}
let title = ref("");
let ruleFormRef = ref(null);
let richPageRef = ref(null); //富文本
function initFun(type, row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }

  if (type == "add") {
    ruleForm.value = {};
    title.value = "新增";
    nextTick(() => {
      richPageRef.value.valueHtml = "";
    });
  } else {
    title.value = "编辑";
    ruleForm.value = Object.assign({}, row);
    nextTick(() => {
      richPageRef.value.valueHtml = row.content;
    });
  }
  console.log(ruleForm.value);
  dialogVisible.value = true;
}

const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      ruleForm.value.content = richPageRef.value.valueHtml;
      if (!ruleForm.value.content) return ElMessage.warning("请输入单页内容！");
      if (!ruleForm.value.id) {
        addApi(ruleForm.value).then((data) => {
          ElMessage.success("新增成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      } else {
        saveApi(ruleForm.value).then((data) => {
          ElMessage.success("修改成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      }
    }
  });
}

onMounted(() => {});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.single-dialog {
  :deep(.el-form-item) {
    width: 50%;
    margin-right: 0;
    padding-right: 10px;
    box-sizing: border-box;
    .el-input {
      width: 100%;
    }
  }
}
</style>
